package com.anysoft.validator;

import com.anysoft.model.Goods;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import java.util.Date;

@Component
public class GoodsValidator implements Validator {
    @Override
    public boolean supports(Class<?> aClass) {
        // 要验证的model,返回值为false则不验证
        // isAssignableFrom方法判断调用者是否为参数的父类
        return Goods.class.isAssignableFrom(aClass);
    }

    @Override
    public void validate(Object o, Errors errors) {
        Goods goods = (Goods) o;
        // 验证必填项商品名和商品你详情
        // goods.gname.required是错误消息属性文件中的编码(国际化后对应的是国际化的信息)
        ValidationUtils.rejectIfEmpty(errors, "gname", "goods.gname.required");
        ValidationUtils.rejectIfEmpty(errors, "gdescription", "goods.gdescription.required");
        // 验证商品价格
        if (goods.getGprice() > 100 || goods.getGprice() < 0) {
            errors.rejectValue("gprice", "gprice.invalid");
        }
        // 验证商品添加日期
        Date goodsDate = goods.getGdate();
        if (goodsDate != null && goodsDate.after(new Date())) {
            errors.rejectValue("gdate", "gdate.invalid");
        }
    }
}
